package view;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.AccountException;
import model.LoginException;

import controller.Cashier;

/**
 * Servlet implementation class AccountServlet
 */
public class AccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private Cashier cashier = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AccountServlet() {
        super();
        cashier = Cashier.getInstance();
        // TODO Auto-generated constructor stub
    }

    /**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String forward = "/Controller.jsp";
		String addAccountStatus = "Conta criada";
		try {
			cashier.createAccount((String)request.getSession().getAttribute("login"), request.getParameter("label"), request.getParameter("agency"), request.getParameter("account"));
		} catch (AccountException e) {
			addAccountStatus = e.getMessage();
		} catch (LoginException e) {
			addAccountStatus = "<font color=\"#FF0000\">Deve fazer login novamente</font>";
		}
		
		request.setAttribute("addAccountStatus", addAccountStatus);
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(forward);
		if (dispatcher != null) {
			dispatcher.forward(request, response);
		}
		
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String forward = "/Controller.jsp";
		
		if(request.getParameter("exibirConta") != null){
			try {
				
				cashier.generateReport(null, null, null, request.getParameter("exibirConta"));
				if(request.getSession().getAttribute("exibirConta") != null){
					request.getSession().removeAttribute("exibirConta");
				}
				request.getSession().setAttribute("exibirConta", request.getParameter("exibirConta"));
			} catch (AccountException e) {}
		}
		String[] removed = request.getParameterValues("remover");
		if(removed != null){
			if(removed.length > 0){
				for (int i = 0; i < removed.length; i++) {
					try {
						cashier.removeAccount(removed[i]);
					} catch (AccountException e) {}
				}
				
			}
		}
		
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(forward);
		if (dispatcher != null) {
			dispatcher.forward(request, response);
		}
		
	}

}
